package com.sun.cart.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.cart.service.TbCatService;
import com.sun.commons.pojo.TbItemVO;
import com.sun.commons.utils.ActionUtils;

@Controller
public class CarController {
	
	@Resource
	private TbCatService tbCatService;

	@RequestMapping("/cart/add/{itemId}.html")
	public String cartAdd(Integer num,@PathVariable Long itemId,HttpServletRequest request){
		try {
			tbCatService.addTbItemInCart(itemId, num, request);
		} catch (Exception e) {
			e.printStackTrace();
			return "error/exception";
		}
		return "cartSuccess";
	}
	
	@RequestMapping("/cart/cart.html")
	public String cartPage(HttpServletRequest request,Model retmodel){
		List<TbItemVO> listdata = tbCatService.listCartTbitem(request);
		retmodel.addAttribute("cartList", listdata);
		return "cart";
	}
	
	@ResponseBody
	@RequestMapping("/cart/update/num/{itemId}/{num}.action")
	public void updateCartItemNum(@PathVariable Long itemId,@PathVariable int num,HttpServletRequest request){
		tbCatService.updateTbItemCart(itemId, num, request);
	}
	
	@ResponseBody
	@RequestMapping("/cart/delete/{itemIds}.action")
	public Map<String,Object> deleteCartItem(@PathVariable String itemIds,HttpServletRequest request){
		if(tbCatService.deleteTbItemCart(itemIds, request)){
			return ActionUtils.ajaxSuccess(null, null);
		}
		return ActionUtils.ajaxFail(null, null);
	}
	
	@ResponseBody
	@RequestMapping("/cart/info")
	public Object cartInfo(HttpServletRequest request,String callback){
		List<TbItemVO> listdata = tbCatService.listCartTbitem(request);
		MappingJacksonValue jsonp = new MappingJacksonValue(ActionUtils.ajaxSuccess("OK", listdata));
		jsonp.setJsonpFunction(callback);
		return jsonp;
	}
}
